package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.WeChatServiceConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController("userUserController")
@RequestMapping("user/user")
@Api(tags = "用户接口")
@Slf4j
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserService userService;
    /**
     * 微信登录
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信登录:{}",userLoginDTO);
        String code = userLoginDTO.getCode();
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put(WeChatServiceConstant.APPID,weChatProperties.getAppid());
        paramMap.put(WeChatServiceConstant.SECRET,weChatProperties.getSecret());
        paramMap.put(WeChatServiceConstant.JS_CODE,code);
        paramMap.put(WeChatServiceConstant.GRANT_TYPE,WeChatServiceConstant.GRANT_TYPE_DEFAULT_VALUE);
        String json = HttpClientUtil.doGet(WeChatServiceConstant.WX_LOGIN_ADDRESS, paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = (String) jsonObject.get(WeChatServiceConstant.OPENID);
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user=userService.login(openid);
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
    /**
     * 微信退出
     */
    @PostMapping("/logout")
    public Result<Object> logout(){
        log.info("用户退出");
        return Result.success();
    }
}
